package cn.xscrum.vtsp.service.impl;

import cn.xscrum.common.core.text.Convert;
import cn.xscrum.common.utils.DateUtils;
import cn.xscrum.vtsp.domain.VtspVolunteer;
import cn.xscrum.vtsp.mapper.VtspApplyMapper;
import cn.xscrum.vtsp.service.IVtspApplyService;
import cn.xscrum.vtsp.service.IVtspMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VtspApplyServiceImpl implements IVtspApplyService {

    @Autowired
    private VtspApplyMapper vtspApplyMapper;

    @Autowired
    private IVtspMessageService vtspMessageService;

    /**
     * 查询志愿者信息
     *
     * @param volunteerId 志愿者信息ID
     * @return 志愿者信息
     */
    @Override
    public VtspVolunteer selectVtspVolunteerById(Long volunteerId) {
        return vtspApplyMapper.selectVtspVolunteerById(volunteerId);
    }

    /**
     * 查询志愿者信息列表
     *
     * @param vtspVolunteer 志愿者信息
     * @return 志愿者信息
     */
    @Override
    public List<VtspVolunteer> selectVtspVolunteerList(VtspVolunteer vtspVolunteer)
    {
        return vtspApplyMapper.selectVtspVolunteerList(vtspVolunteer);
    }

    /**
     * 修改志愿者信息
     *
     * @param vtspVolunteer 志愿者信息
     * @return 结果
     */
    @Override
    public int updateVtspVolunteer(VtspVolunteer vtspVolunteer)
    {
        vtspVolunteer.setUpdateTime(DateUtils.getNowDate());
        return vtspApplyMapper.updateVtspVolunteer(vtspVolunteer);
    }

    /**
     * 批量拒绝 入队申请(member_state 1 -> 3)
     *
     * @param volunteerIds 需要修改的数据ID
     * @return 结果
     */
    public int refuseVtspVolunteerByIds(String volunteerIds, String applyInfo) {
        //拒绝入队申请
        int row = vtspApplyMapper.refuseVtspVolunteerByIds(Convert.toStrArray(volunteerIds), applyInfo);
        //对批量申请入队的信息进行消息持久化
        if (row > 0){
            addMessage(volunteerIds);
        }
        return row;
    }

    /**
     * 批量同意 入队申请(member_state 1 -> 6)
     *
     * @param volunteerIds 需要修改的数据ID
     * @return 结果
     */
    public int acceptVtspVolunteerByIds(String volunteerIds) {
        //同意入队申请
        int row = vtspApplyMapper.acceptVtspVolunteerByIds(Convert.toStrArray(volunteerIds));
        //对批量申请入队的信息进行消息持久化
        if (row > 0){
            addMessage(volunteerIds);
        }
        //对通过志愿者执行发送消息到可视化工具    状态6，userId-页面申请的连接id（对正式志愿者及其他进行更新）
        vtspMessageService.sendMessage(6,null,7L);
        return row;
    }

    /**
     * 添加拒绝、同意入队的信息持久化记录
     *
     * @param volunteerIds 批量操作的id数组
     */
    private void addMessage(String volunteerIds){
        //将字符串转换成数组
        String[] strings = Convert.toStrArray(volunteerIds);
        //遍历数组，依次添加消息记录
        for (String string : strings) {
            //0-入队申请
            vtspMessageService.sendMessage(0,null,Long.valueOf(string));
        }
    }
}
